package com.example.basesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.basesystem.common.Result;
import com.example.basesystem.entity.SysRole;
import com.example.basesystem.service.SysRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 角色控制器
 */
@Tag(name = "角色管理", description = "角色相关接口")
@RestController
@RequestMapping("/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 分页查询角色列表
     */
    @Operation(summary = "分页查询角色列表", description = "分页查询角色列表接口")
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public Result<Page<SysRole>> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "角色名称") @RequestParam(required = false) String roleName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        Page<SysRole> page = new Page<>(current, size);
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(roleName), SysRole::getRoleName, roleName)
                .eq(status != null, SysRole::getStatus, status)
                .orderByDesc(SysRole::getCreateTime);
        Page<SysRole> rolePage = sysRoleService.page(page, queryWrapper);
        return Result.success(rolePage);
    }

    /**
     * 查询所有角色
     */
    @Operation(summary = "查询所有角色", description = "查询所有角色接口")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public Result<List<SysRole>> list() {
        List<SysRole> roleList = sysRoleService.list();
        return Result.success(roleList);
    }

    /**
     * 根据ID查询角色
     */
    @Operation(summary = "根据ID查询角色", description = "根据ID查询角色接口")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:role:info')")
    public Result<SysRole> getById(@PathVariable Long id) {
        SysRole role = sysRoleService.getById(id);
        return Result.success(role);
    }

    /**
     * 新增角色
     */
    @Operation(summary = "新增角色", description = "新增角色接口")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:role:add')")
    public Result<Object> add(@Validated @RequestBody SysRole role) {
        role.setCreateTime(LocalDateTime.now());
        role.setStatus(1);
        role.setIsDeleted(0);
        boolean result = sysRoleService.save(role);
        return result ? Result.success() : Result.error("新增角色失败");
    }

    /**
     * 修改角色
     */
    @Operation(summary = "修改角色", description = "修改角色接口")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:role:update')")
    public Result<Object> update(@Validated @RequestBody SysRole role) {
        role.setUpdateTime(LocalDateTime.now());
        boolean result = sysRoleService.updateById(role);
        return result ? Result.success() : Result.error("修改角色失败");
    }

    /**
     * 删除角色
     */
    @Operation(summary = "删除角色", description = "删除角色接口")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public Result<Object> delete(@PathVariable Long id) {
        boolean result = sysRoleService.removeById(id);
        return result ? Result.success() : Result.error("删除角色失败");
    }

    /**
     * 分配角色菜单权限
     */
    @Operation(summary = "分配角色菜单权限", description = "分配角色菜单权限接口")
    @PostMapping("/assign-menu/{id}")
    @PreAuthorize("hasAuthority('sys:role:assign-menu')")
    public Result<Object> assignMenu(@PathVariable Long id,
                                    @Parameter(description = "菜单ID列表") @RequestBody List<Long> menuIds) {
        boolean result = sysRoleService.assignRoleMenu(id, menuIds);
        return result ? Result.success() : Result.error("分配角色菜单权限失败");
    }
}